import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
class Request{                      //映射 json出java请求
    public String username ;    //创建出Java对象
    public String password ;    // 属性要 public ,Jackson只会处理 public, 否则要get和set方法;
}
class Response{           //响应, 用来映射出 json
    public boolean ok ;
}



@WebServlet("/json")
public class JsonParameterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          // 约定json传输数据的格式
          // post/json
          //Content-Type: application/json

        //json请求格式
        //{
        // username:"xxx",
        // password:"xxx"
        // }

          // 约定 响应格式
          // {
        //    ok:true
        // }

        //构造出 对象映射器
        ObjectMapper objectMapper = new ObjectMapper() ;
         //通过 readValue方法把json映射成 Request对象 ;
        Request request =  objectMapper.readValue(req.getInputStream(),Request.class);
        System.out.println("username:"+request.username +"  password:"+request.password);

        //把响应,映射成 json;
        //创建响应对象
        Response response = new Response() ;
        response.ok = true ;
        //转换响应对象 ;
         String respJson = objectMapper.writeValueAsString(response) ;

         //设置utf8编码 ;
        resp.setContentType("application/json; charset=utf8");
        //返回响应
    }
}
